package com.shqcjd.preinstallglass.ui.activity.remote;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Chronometer;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.afollestad.materialdialogs.MaterialDialog;
import com.open.androidtvwidget.bridge.EffectNoDrawBridge;
import com.open.androidtvwidget.bridge.OpenEffectBridge;
import com.open.androidtvwidget.view.FrameMainLayout;
import com.open.androidtvwidget.view.MainUpView;
import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.api.ApiService;
import com.shqcjd.preinstallglass.app.MyApp;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallglass.model.ResponseData;
import com.shqcjd.preinstallglass.model.eventbus.CreateVideotape;
import com.shqcjd.preinstallglass.ui.base.BaseActivity;
import com.shqcjd.preinstallglass.ui.base.BasePresenter;
import com.shqcjd.preinstallglass.util.PrefUtils;
import com.shqcjd.preinstallglass.util.ToastUtils;
import com.shqcjd.preinstallglass.util.VideotapeUtil;
import com.shqcjd.preinstallglass.widget.BadgeHelper;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import io.reactivex.disposables.Disposable;

/**
 * 远程指导页面
 */
public class PushVideoActivity extends BaseActivity{


    @BindView(R.id.remote_video_view_container)
    FrameLayout container;
    @BindView(R.id.cb_call_mute_button)
    CheckBox cbCallMuteButton;
    @BindView(R.id.ll_mute_btn)
    LinearLayout llMuteBtn;
    @BindView(R.id.ll_file_btn)
    LinearLayout llFileBtn;
    @BindView(R.id.chronometer_layout)
    Chronometer chronometer_layout;
    @BindView(R.id.ll_hang_up_btn)
    LinearLayout llHangUpBtn;
    private Context mContext;
    private String channelID;
    private String expertID;
    private int equipmentId;
    private int taskId;
    private int userID;
    private BadgeHelper badgeHelper;
    private AgoraAPIOnlySignal mAgoraAPI;
    private RtcEngine mRtcEngine;

    private boolean timerFlag = true;

    private final int TIME = 1000;
    private int timingNum = 20;
    private Handler finishHandler = new Handler();
    private Runnable finishRunnable = new Runnable() {
        @Override
        public void run() {
            Logger.i("计时:" + timingNum);
            if (timingNum == 1) {
                ToastUtils.showShort(mContext, "网络信号不稳定,无法进行远程指导");
                finishHandler.removeCallbacks(finishRunnable);
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        finish();
                    }
                }, 2000);
            } else {
                timingNum--;
                finishHandler.postDelayed(finishRunnable, TIME);
            }
        }
    };

    private int unReadMsgNum = 0;//未读消息数量
    private boolean isHasFile = false;//是否有发送文件，用于判断进入文件列表

    @BindView(R.id.mainUpView1)
    MainUpView mMainUpView;
    @BindView(R.id.main_lay)
    FrameMainLayout main_lay11;
    OpenEffectBridge mOpenEffectBridge;
    View mOldFocus;


    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_push_video;
    }

    @Override
    public void initView() {
        mContext = this;

        channelID = getIntent().getStringExtra("channelID");
        expertID = getIntent().getStringExtra("expertID");
        equipmentId = getIntent().getIntExtra("equipmentId", -1);
        taskId = getIntent().getIntExtra("taskId", -1);
        userID = PrefUtils.getInt(mContext, PrefUtils.USER_ID, -1);

        cbCallMuteButton.setOnCheckedChangeListener(oncheckChangeListerener);

        //消息红点
        badgeHelper = new BadgeHelper(this)
                .setBadgeType(BadgeHelper.Type.TYPE_TEXT)
                .setBadgeOverlap(true, false);
        badgeHelper.bindToTargetView(llFileBtn);
        badgeHelper.setVisibility(View.GONE);

        mMainUpView.setEffectBridge(new EffectNoDrawBridge());
        mOpenEffectBridge = (OpenEffectBridge) mMainUpView.getEffectBridge();
        Drawable testDrawable = null;
        mMainUpView.setUpRectDrawable(testDrawable); // 设置边框图片
        mMainUpView.setUpRectResource(R.drawable.test_rectangle); // 设置边框图片.
        main_lay11.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
            @Override
            public void onGlobalFocusChanged(final View oldFocus, final View newFocus) {

                if (newFocus != null)
//                    newFocus.bringToFront(); // 防止放大的view被压在下面. (建议使用MainLayout)
                    mMainUpView.setFocusView(newFocus, mOldFocus, 1.0f);
                mOldFocus = newFocus; // 4.3以下需要自己保存.
                // 测试是否让边框绘制在下面，还是上面. (建议不要使用此函数)
//                if (newFocus != null) {
//                    testTopDemo(newFocus, scale);
//                }
            }
        });

//        checkPermissions();
        initRtcEngine();
    }

    private void initRtcEngine() {
        mAgoraAPI = MyApp.the().getmAgoraAPI();
        mRtcEngine = MyApp.the().getmRtcEngine();
        //加入信令频道
        mAgoraAPI.channelJoin(channelID);
        Logger.i("roomId: 远程指导:"+channelID);
        setupLocalVideo();
        CreateVideotape createVideotape = new CreateVideotape(this, channelID);
        //开启音视频
        VideotapeUtil.getInstance().createVideotape(this, false, createVideotape);
        VideotapeUtil.getInstance().setOnEngineInterface(new VideotapeUtil.OnEngineInterface() {
            @Override
            public void onUserJoined(int uid, int elapsed) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (timerFlag) {
                            timerFlag = false;
                            createGuide();//调用后台创建远程指导接口
                        }
                    }
                });
            }

            @Override
            public void onUserOffline(int uid, int reason) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        onRemoteUserOffline(uid);
                    }
                });
            }
        });
    }

//    /**
//     * 检测权限
//     */
//    private void checkPermissions() {
//        RxPermissions permissions = new RxPermissions(this);
//        permissions.setLogging(true);
//        permissions.request(Manifest.permission.RECORD_AUDIO,
//                Manifest.permission.CAMERA,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                .subscribe(new Consumer<Boolean>() {
//                    @Override
//                    public void accept(Boolean aBoolean) throws Exception {
//                        if (aBoolean) {
//                            initAgoraEngineAndJoinChannel();
//                        } else {
//                            ToastUtils.showShort(mContext, "缺少远程指导必要权限");
//                            finish();
//                        }
//                    }
//                });
//    }
//
//    /**
//     * 初始化远程指导
//     */
//    private void initAgoraEngineAndJoinChannel() {
//        //初始化视频
//        initializeAgoraEngine();     // 步骤1
//        setupVideoProfile();         // 步骤2
//        MyApp.the().setOnAgoraEngineInterface(this);
//        setupLocalVideo();          // 步骤3
//        joinChannel();               // 步骤4
//
//        finishHandler.postDelayed(finishRunnable, TIME);
//    }
//
//    private void joinChannel() {
//        //加入信令频道
//        mAgoraAPI.channelJoin(channelID);
//        //加入视频频道
//        Logger.i("加入房间号:" + channelID);
//        int i1 = mRtcEngine.leaveChannel();
//        int i = mRtcEngine.joinChannel(null, channelID, "Extra Optional Data", userID);// if you do not specify the uid, we will generate the uid for you
//        Logger.i("加入频道码:" + i + "  离开频道:" + i1);
//    }
//

    /**
     * 设置本地视频视频
     */
    private void setupLocalVideo() {
//        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
////        surfaceView.setZOrderMediaOverlay(true);
//        container.addView(surfaceView);
//        //设置本地视频视频
//        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, 0));
////        //镜像问题调用
        mRtcEngine.setParameters("{\"che.video.localViewMirrorSetting\":\"disableMirror\"}");
//        mRtcEngine.startPreview();

        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
        container.addView(surfaceView);
        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, 0));
        container.setVisibility(View.VISIBLE);
        mRtcEngine.startPreview();
        //转换摄像头
//        mRtcEngine.switchCamera();
    }
//
//    private void setupVideoProfile() {
//        mRtcEngine.enableVideo();
//
//        VideoEncoderConfiguration.VideoDimensions vd_1280x720 = VideoEncoderConfiguration.VD_1280x720;
//        VideoEncoderConfiguration.FRAME_RATE frameRateFps15 = VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15;
//        int standardBitrate = VideoEncoderConfiguration.STANDARD_BITRATE;
//        VideoEncoderConfiguration.ORIENTATION_MODE orientationModeAdaptive = VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_LANDSCAPE;
//        VideoEncoderConfiguration videoEncoderConfiguration = new VideoEncoderConfiguration(vd_1280x720, frameRateFps15, standardBitrate, orientationModeAdaptive);
//        mRtcEngine.setVideoEncoderConfiguration(videoEncoderConfiguration);
//    }
//
//    private void initializeAgoraEngine() {
//        mAgoraAPI = MyApp.the().getmAgoraAPI();
//        mRtcEngine = MyApp.the().getmRtcEngine();
//        if (mRtcEngine != null) {
//            mRtcEngine.setLogFile("/sdcard/sdklog.txt");
//        }
//    }


    /**
     * 控制静音
     */
    private CompoundButton.OnCheckedChangeListener oncheckChangeListerener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mRtcEngine.muteLocalAudioStream(isChecked);
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        addSignalingCallback();
    }

    private void addSignalingCallback() {
        if (mAgoraAPI == null) {
            return;
        }

        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {

            /**
             * 收到频道消息回调
             * @param channelID 频道名
             * @param account 客户端定义的用户账号
             * @param uid 固定填 0
             * @param msg 消息正文
             */
            @Override
            public void onMessageChannelReceive(String channelID, final String account, final int uid, final String msg) {
                super.onMessageChannelReceive(channelID, account, uid, msg);
                Logger.i("接收到频道消息: account:" + account + " uid:" + uid + " msg:" + msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        unReadMsgNum++;
                        isHasFile = true;
                        if (badgeHelper.getVisibility() == View.GONE) {
                            badgeHelper.setVisibility(View.VISIBLE);
                        }
                        badgeHelper.setBadgeNumber(unReadMsgNum);//数字
                    }
                });
            }

            @Override
            public void onLogout(final int i) {
                Logger.i("Agora onLogout:" + i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGOUT_E_KICKED) { // 账号其他地方登录
                            ToastUtils.showShort(mContext, "用户在别处登录");
                            finish();
                        } else if (i == IAgoraAPI.ECODE_LOGOUT_E_NET) { // 网络问题
                            ToastUtils.showShort(mContext, "网络异常，可能无法收到对方文件！");
                        }
                    }
                });

            }

        });
    }


    @OnClick({R.id.ll_mute_btn, R.id.ll_file_btn, R.id.ll_hang_up_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_mute_btn://静音
                cbCallMuteButton.setChecked(!cbCallMuteButton.isChecked());
                break;
            case R.id.ll_file_btn://文件列表
                if (isHasFile) {
                    Intent intent = new Intent(PushVideoActivity.this, FileListActivity.class);
                    intent.putExtra("channelID", channelID);
                    startActivity(intent);
                    unReadMsgNum = 0;
                    badgeHelper.setVisibility(View.GONE);
                } else {
                    ToastUtils.showShort(mContext, "暂无指导文件!");
                }
                break;
            case R.id.ll_hang_up_btn://挂断
                showDialog();
                break;
        }
    }


//    @Override
//    public void onFirstRemoteVideoDecoded(int uid, int width, int height, int elapsed) {
//
//    }
//
//    @Override
//    public void onUserJoined(int uid, int elapsed) {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (timerFlag) {
//                    timerFlag = false;
//                    createGuide();//调用后台创建远程指导接口
//                }
//
//            }
//        });
//    }
//
//
//    @Override
//    public void onUserOffline(int uid, int reason) {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                onRemoteUserOffline(uid);
//            }
//        });
//    }
//
//
//    //远端用户暂停/重新发送视频流回调。
//    @Override
//    public void onUserMuteVideo(int uid, boolean muted) {
//
//    }
//
//    @Override
//    public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
//
//    }
//
//    @Override
//    public void onLeaveChannel(IRtcEngineEventHandler.RtcStats stats) {
//
//    }
//
//    @Override
//    public void onError(int err) {
//
//    }


    private void createGuide() {
        Map<String, String> map = new HashMap<>();
        map.put("user_id", userID + "");
        map.put("expert_id", expertID);

        if (equipmentId != -1) {
            map.put("equipment_id", equipmentId + "");
            map.put("flights_task_id", taskId + "");
        } else {
            map.put("equipment_id", "");
            map.put("flights_task_id", "");
        }

        map.put("room_id", channelID);
        ApiService.createGuide(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("创建远程指导中...");
                    }

                    @Override
                    public void _onNext(ResponseData<String> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            finishHandler.removeCallbacks(finishRunnable);//移除定时关闭
                            chronometer_layout.setBase(SystemClock.elapsedRealtime());//计时器清零
                            chronometer_layout.start();
                            guideHandle("0");
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }


                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void guideHandle(String handle) {
        Map<String, String> map = new HashMap<>();
        map.put("roomId", channelID);
        map.put("operation", handle);//	0:开始录制、1:结束录制
        map.put("guideStatus", "0");//0:专家指导,1:全程录像，operation为(0:开始录制)该参数有效
        ApiService.handleGuide(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        if (handle.equals("1")) {
                            showWaitingDialog("结束中");
                        } else {
                            showWaitingDialog("开启录制");
                        }

                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (handle.equals("1")) {
                            finish();
                        }
                        hideWaitingDialog();
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        if (handle.equals("1")) {
                            finish();
                        }
                        hideWaitingDialog();
                    }
                });
    }

    private void onRemoteUserOffline(int uid) {
        finish();
        ToastUtils.showShort(mContext, "指导结束，对方已离开");
    }

    OpenEffectBridge mOpenEffectBridgeChild;
    View mOldFocusChild;
    private void showDialog() {
        final MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.follow_custome_view, false)
                .show();
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = 630;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        dialog.onWindowAttributesChanged(lp);
        window.setAttributes(lp);

        View customeView = dialog.getCustomView();

        Button follow = (Button) customeView.findViewById(R.id.btn_follow);
        Button cancel = customeView.findViewById(R.id.btn_cancel);
        MainUpView mMainUpViewChild = customeView.findViewById(R.id.mainUpView1);
        FrameMainLayout main_lay11Child = customeView.findViewById(R.id.main_lay);

        follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                finish();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        mMainUpViewChild.setEffectBridge(new EffectNoDrawBridge());
        mOpenEffectBridge = (OpenEffectBridge) mMainUpViewChild.getEffectBridge();
        Drawable testDrawable = null;
        mMainUpViewChild.setUpRectDrawable(testDrawable); // 设置边框图片
        mMainUpViewChild.setUpRectResource(R.drawable.test_rectangle); // 设置边框图片.
        main_lay11Child.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
            @Override
            public void onGlobalFocusChanged(final View oldFocus, final View newFocus) {

                if (newFocus != null)
//                    newFocus.bringToFront(); // 防止放大的view被压在下面. (建议使用MainLayout)
                    mMainUpViewChild.setFocusView(newFocus, mOldFocusChild, 1.0f);
                mOldFocusChild = newFocus; // 4.3以下需要自己保存.
                // 测试是否让边框绘制在下面，还是上面. (建议不要使用此函数)
//                if (newFocus != null) {
//                    testTopDemo(newFocus, scale);
//                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (finishHandler != null) {
            finishHandler.removeCallbacks(finishRunnable);//移除定时关闭
        }

        mAgoraAPI.channelLeave(channelID);
        VideotapeUtil.getInstance().finishVideotape(new VideotapeUtil.OnFinishVideotapeListener() {
            @Override
            public void onInitFinish() {

            }

            @Override
            public void onFinishVideotape() {

            }
        });
//        if (mRtcEngine != null) {
//            mRtcEngine.switchCamera();
//            mRtcEngine.stopPreview();
//            mRtcEngine.leaveChannel();//离开频道
//        }
//        mRtcEngine = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
